package com.xs.shop.user.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xs.shop.common.exceptions.BusinessException;
import com.xs.shop.common.exceptions.enums.Resp;
import com.xs.shop.user.model.dto.AdminLoginDTO;
import com.xs.shop.user.model.entity.Admin;
import com.xs.shop.user.model.entity.Role;
import com.xs.shop.user.service.mapper.AdminMapper;
import com.xs.shop.user.service.service.AdminService;
import com.xs.shop.user.service.service.RoleService;
import com.xs.shop.user.service.utils.JwtUtil;
import com.xs.shop.user.model.vo.AdminLoginVO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 管理员用户表 服务实现类
 * </p>
 *
 * @author xs
 * @since 2025-07-07
 */
@Service
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private RoleService roleService;

    @Resource
    private HttpServletRequest request;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public AdminLoginVO login(AdminLoginDTO adminLoginDTO) {
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasText(adminLoginDTO.getUsername()), Admin::getMobile,adminLoginDTO.getUsername());
        Admin admin = this.getOne(wrapper);

        if (admin == null) {
            log.info("账号不存在");
            throw new BusinessException(Resp.INVALID_USERNAME);
        }
        log.info("密码密文:{}",passwordEncoder.encode(adminLoginDTO.getPassword()));
        if(!passwordEncoder.matches(adminLoginDTO.getPassword(),admin.getPassword())) {
            throw new BusinessException(Resp.INVALID_PASSWORD);
        }
        Role role = this.roleService.getRoleByAdminId(admin.getId());
        Claims claims = Jwts.claims();
        claims.put("adminId",admin.getId());
        claims.put("roleId",role.getId());
        return new AdminLoginVO(
                jwtUtil.generateAccessToken(claims),
                jwtUtil.generateRefreshToken(claims)
        );
    }

    //    @Override
//    public void updatePassword(AdminUpdatePasswordDTO adminUpdatePasswordDTO) {
//        // 获取当前管理员ID
//        Long adminId = BaseContextHandler.get();
//        if (adminId == null) {
//            log.error("未获取到当前管理员ID");
//            throw new BusinessException(Resp.UNAUTHORIZED);
//        }
//
//        // 查询管理员信息
//        Admin admin = this.getById(adminId);
//        if (admin == null) {
//            log.error("管理员不存在, ID: {}", adminId);
//            throw new BusinessException(Resp.INVALID_USERNAME);
//        }
//
//        // 验证旧密码
//        if (!passwordEncoder.matches(adminUpdatePasswordDTO.getOldPassword(), admin.getPassword())) {
//            log.warn("管理员密码修改失败: 旧密码不匹配, ID: {}", adminId);
//            throw new BusinessException(Resp.INVALID_PASSWORD);
//        }
//
//        // 加密新密码
//        String encodedPassword = passwordEncoder.encode(adminUpdatePasswordDTO.getNewPassword());
//
//        // 更新密码
//        Admin updateAdmin = new Admin();
//        updateAdmin.setId(adminId);
//        updateAdmin.setPassword(encodedPassword);
//        if (!this.updateById(updateAdmin)) {
//            log.error("管理员密码更新失败, ID: {}", adminId);
//            throw new BusinessException(Resp.UPDATE_FAILED);
//        }
//
//        log.info("管理员密码修改成功, ID: {}", adminId);
//    }


    @Override
    public boolean checkToken() {
        String accessToken = request.getHeader("Authorization");
        String result = jwtUtil.validateAccessToken(accessToken);
        log.info("valid result: {}",result);
        return "Valid".equals(result);
    }

}
